package com.itpan.Utils;



import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.itpan.Entity.Customer;
import com.itpan.Service.CustomerService;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.List;
@Service
public class CustomerExcelListener extends AnalysisEventListener<Customer> {

    private final CustomerService customerService;
    private List<Customer> customerList = new ArrayList<>();

    private final EntityValidate entityValidate;

    public CustomerExcelListener(CustomerService customerService, EntityValidate entityValidate) {
        this.customerService = customerService;
        this.entityValidate = entityValidate;
    }

    @Override
    public void invoke(Customer customer, AnalysisContext context) {
        // 校验数据是否有效
        if (isValidCustomer(customer) && !isAlreadyRegistered(customer) &&entityValidate.isValidateOfCustomer(customer)) {
            customerList.add(customer);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 读取结束后的操作，可以进行批量保存或其他处理
        if (!customerList.isEmpty()) {
            System.out.println("收集完成");
            customerService.addAll(customerList);

        }
    }

    private boolean isValidCustomer(Customer customer) {
        // 检查每个字段是否为null或空
        return customer.getCustomerID() != null
                && customer.getCustomerName() != null
                && customer.getCustomerShortName() != null
                && customer.getAddress() != null
                && customer.getCompanyPhone() != null
                && customer.getEmail() != null
                && customer.getContactPerson() != null
                && customer.getContactPhone() != null
                && customer.getNotes() != null;
    }

    private boolean isAlreadyRegistered(Customer customer) {
        Customer existingCustomer = customerService.getById(customer.getCustomerID());
        return existingCustomer != null;
    }
}
